<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI对话助手</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- 引入Marked.js用于Markdown渲染 -->
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <!-- 引入Highlight.js用于代码高亮 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/github.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
    <style>
        .message-fade-in {
            animation: fadeIn 0.3s ease-in-out;
        }
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        .loading-dots:after {
            content: '';
            animation: dots 1.5s steps(5, end) infinite;
        }
        @keyframes dots {
            0%, 20% { content: '.'; }
            40% { content: '..'; }
            60%, 100% { content: '...'; }
        }
        /* Markdown 样式 */
        .markdown-content {
            line-height: 1.6;
        }
        .markdown-content h1, .markdown-content h2, .markdown-content h3 {
            margin-top: 1em;
            margin-bottom: 0.5em;
            font-weight: 600;
        }
        .markdown-content h1 { font-size: 1.5em; }
        .markdown-content h2 { font-size: 1.3em; }
        .markdown-content h3 { font-size: 1.1em; }
        .markdown-content p { margin-bottom: 1em; }
        .markdown-content ul, .markdown-content ol {
            margin-bottom: 1em;
            padding-left: 2em;
        }
        .markdown-content li { margin-bottom: 0.5em; }
        .markdown-content blockquote {
            border-left: 4px solid #e5e7eb;
            padding-left: 1em;
            margin: 1em 0;
            color: #6b7280;
        }
        .markdown-content code {
            background-color: #f3f4f6;
            padding: 0.2em 0.4em;
            border-radius: 0.25em;
            font-size: 0.9em;
        }
        .markdown-content pre {
            background-color: #f8f9fa;
            border: 1px solid #e5e7eb;
            border-radius: 0.5em;
            padding: 1em;
            overflow-x: auto;
            margin: 1em 0;
        }
        .markdown-content pre code {
            background: none;
            padding: 0;
        }
        .markdown-content table {
            border-collapse: collapse;
            width: 100%;
            margin: 1em 0;
        }
        .markdown-content th, .markdown-content td {
            border: 1px solid #e5e7eb;
            padding: 0.5em;
            text-align: left;
        }
        .markdown-content th {
            background-color: #f9fafb;
            font-weight: 600;
        }
        /* Think块样式 */
        .think-block {
            background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
            border: 1px solid #bae6fd;
            border-radius: 12px;
            padding: 1.5rem;
            margin: 1rem 0;
            position: relative;
            font-size: 0.9em;
            line-height: 1.5;
        }
        .think-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 0.75rem;
            padding-bottom: 0.5rem;
            border-bottom: 1px solid #bae6fd;
        }
        .think-title {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-weight: 600;
            color: #0369a1;
            font-size: 0.85em;
        }
        .think-toggle {
            background: none;
            border: none;
            color: #0369a1;
            cursor: pointer;
            padding: 0.25rem 0.5rem;
            border-radius: 0.25rem;
            font-size: 0.8em;
            transition: all 0.2s;
        }
        .think-toggle:hover {
            background-color: #bae6fd;
        }
        .think-content {
            color: #0c4a6e;
            white-space: pre-wrap;
            font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
        }
        .think-content.collapsed {
            display: -webkit-box;
            -webkit-line-clamp: 3;
            -webkit-box-orient: vertical;
            overflow: hidden;
        }
        .think-icon {
            width: 16px;
            height: 16px;
        }
    </style>
</head>
<body class="bg-gray-50 h-screen flex">
<!-- 侧边栏 -->
<div class="w-64 bg-white border-r border-gray-200 flex flex-col h-full">
    <div class="p-4 border-b border-gray-200">
        <button id="newChatBtn" class="w-full bg-blue-500 hover:bg-blue-600 text-white py-2 px-4 rounded-lg flex items-center justify-center transition-colors">
            <i class="fas fa-plus mr-2"></i>新建聊天
        </button>
    </div>
    <div class="flex-1 overflow-y-auto p-2">
        <h2 class="text-sm font-semibold text-gray-500 px-2 py-1">最近聊天</h2>
        <div id="chatList" class="space-y-1">
            <!-- 聊天列表会动态生成 -->
        </div>
    </div>
    <div class="p-4 border-t border-gray-200">
        <button id="uploadTabBtn" class="w-full bg-green-500 hover:bg-green-600 text-white py-2 px-4 rounded-lg flex items-center justify-center transition-colors">
            <i class="fas fa-upload mr-2"></i>上传知识库
        </button>
    </div>
</div>

<!-- 主内容区域 -->
<div class="flex-1 flex flex-col h-full">
    <!-- 对话区域 -->
    <div id="chatArea" class="flex-1 overflow-y-auto p-6">
        <div class="max-w-3xl mx-auto space-y-6">
            <!-- 欢迎消息 -->
            <div class="text-center py-12">
                <h1 class="text-3xl font-bold text-gray-800 mb-2">AI对话助手</h1>
                <p class="text-gray-600">选择左侧聊天或新建对话开始交流</p>
            </div>
            <!-- 消息列表会动态生成 -->
            <div id="messageList" class="space-y-6"></div>
        </div>
    </div>

    <!-- 输入区域 -->
    <div class="border-t border-gray-200 bg-white p-4">
        <div class="max-w-3xl mx-auto flex">
            <input
                    type="text"
                    id="messageInput"
                    placeholder="输入一条消息..."
                    class="flex-1 border border-gray-300 rounded-l-lg px-4 py-3 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                    disabled
            >
            <button
                    id="sendBtn"
                    class="bg-blue-500 hover:bg-blue-600 text-white px-6 py-3 rounded-r-lg transition-colors disabled:bg-blue-300"
                    disabled
            >
                <i class="fas fa-paper-plane"></i>
            </button>
        </div>
        <div class="max-w-3xl mx-auto mt-2 text-xs text-gray-500 text-center">
            按 Enter 发送消息
        </div>
    </div>
</div>

<!-- 知识库上传区域 -->
<div id="uploadArea" class="hidden flex-1 flex flex-col h-full bg-white">
    <div class="p-4 border-b border-gray-200 flex justify-between items-center">
        <h2 class="text-xl font-bold text-gray-800">知识库上传</h2>
        <button id="backToChatBtn" class="text-blue-500 hover:text-blue-700 flex items-center">
            <i class="fas fa-arrow-left mr-2"></i>返回对话
        </button>
    </div>

    <div class="flex-1 overflow-y-auto p-6">
        <div class="max-w-2xl mx-auto bg-white rounded-lg border border-gray-200 p-6">
            <h3 class="text-lg font-semibold text-gray-800 mb-4">上传知识库文件</h3>

            <div class="mb-6">
                <label for="ragTag" class="block text-sm font-medium text-gray-700 mb-2">知识库名称</label>
                <input
                        type="text"
                        id="ragTag"
                        placeholder="请输入知识库名称"
                        class="w-full border border-gray-300 rounded-lg px-4 py-3 focus:outline-none focus:ring-2 focus:ring-green-500 focus:border-transparent"
                >
            </div>

            <div class="mb-6">
                <label class="block text-sm font-medium text-gray-700 mb-2">选择文件</label>
                <div
                        id="dropZone"
                        class="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center cursor-pointer hover:border-green-500 transition-colors"
                >
                    <i class="fas fa-cloud-upload-alt text-4xl text-gray-400 mb-4"></i>
                    <p class="text-gray-600 mb-1">点击选择文件或拖拽到此区域</p>
                    <p class="text-sm text-gray-500">支持格式: .md, .txt, .sql</p>
                    <input type="file" id="fileInput" class="hidden" multiple accept=".md,.txt,.sql">
                </div>
                <div id="fileList" class="mt-4 space-y-2"></div>
            </div>

            <button
                    id="uploadBtn"
                    class="w-full bg-green-500 hover:bg-green-600 text-white py-3 px-4 rounded-lg flex items-center justify-center transition-colors disabled:bg-green-300"
                    disabled
            >
                <i class="fas fa-upload mr-2"></i>开始上传
            </button>

            <div id="uploadStatus" class="mt-4"></div>
        </div>
    </div>
</div>

<!-- 重命名模态框 -->
<div id="renameModal" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
    <div class="bg-white rounded-lg p-6 w-80">
        <h3 class="text-lg font-semibold mb-4">重命名聊天</h3>
        <input
                type="text"
                id="renameInput"
                class="w-full border border-gray-300 rounded-lg px-4 py-2 mb-4 focus:outline-none focus:ring-2 focus:ring-blue-500"
                placeholder="输入新名称"
        >
        <div class="flex justify-end space-x-2">
            <button id="cancelRenameBtn" class="px-4 py-2 text-gray-600 hover:text-gray-800">取消</button>
            <button id="confirmRenameBtn" class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600">确认</button>
        </div>
    </div>
</div>

<script>
    // 配置Marked.js
    marked.setOptions({
        highlight: function(code, lang) {
            if (lang && hljs.getLanguage(lang)) {
                try {
                    return hljs.highlight(code, { language: lang }).value;
                } catch (err) {
                    console.error('代码高亮错误:', err);
                }
            }
            return code;
        },
        breaks: true,
        gfm: true
    });

    // 全局状态
    const state = {
        chats: JSON.parse(localStorage.getItem('aiChats')) || [],
        activeChatId: null,
        currentModel: 'deepseek-r1:1.5b',
        isStreaming: false,
        currentEventSource: null,
        filesToUpload: []
    };

    // DOM 元素
    const elements = {
        chatList: document.getElementById('chatList'),
        messageList: document.getElementById('messageList'),
        messageInput: document.getElementById('messageInput'),
        sendBtn: document.getElementById('sendBtn'),
        newChatBtn: document.getElementById('newChatBtn'),
        uploadArea: document.getElementById('uploadArea'),
        chatArea: document.getElementById('chatArea'),
        uploadTabBtn: document.getElementById('uploadTabBtn'),
        backToChatBtn: document.getElementById('backToChatBtn'),
        ragTag: document.getElementById('ragTag'),
        dropZone: document.getElementById('dropZone'),
        fileInput: document.getElementById('fileInput'),
        fileList: document.getElementById('fileList'),
        uploadBtn: document.getElementById('uploadBtn'),
        uploadStatus: document.getElementById('uploadStatus'),
        renameModal: document.getElementById('renameModal'),
        renameInput: document.getElementById('renameInput'),
        cancelRenameBtn: document.getElementById('cancelRenameBtn'),
        confirmRenameBtn: document.getElementById('confirmRenameBtn')
    };

    // Think块管理器
    const thinkManager = {
        currentThinkContent: '',
        isInThinkBlock: false,

        startThink() {
            this.currentThinkContent = '';
            this.isInThinkBlock = true;
        },

        addThinkContent(content) {
            if (this.isInThinkBlock) {
                this.currentThinkContent += content;
            }
        },

        endThink() {
            this.isInThinkBlock = false;
            const thinkContent = this.currentThinkContent;
            this.currentThinkContent = '';
            return thinkContent;
        },

        renderThinkBlock(thinkContent) {
            if (!thinkContent.trim()) return '';

            // 生成唯一ID用于切换
            const thinkId = 'think-' + Date.now();

            return `
                    <div class="think-block">
                        <div class="think-header">
                            <div class="think-title">
                                <svg class="think-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
                                </svg>
                                AI思考过程
                            </div>
                            <button class="think-toggle" onclick="thinkManager.toggleThink('${thinkId}')">
                                收起
                            </button>
                        </div>
                        <div id="${thinkId}" class="think-content">
                            ${thinkContent}
                        </div>
                    </div>
                `;
        },

        toggleThink(thinkId) {
            const thinkContent = document.getElementById(thinkId);
            const toggleBtn = thinkContent.parentElement.querySelector('.think-toggle');

            if (thinkContent.classList.contains('collapsed')) {
                thinkContent.classList.remove('collapsed');
                toggleBtn.textContent = '收起';
            } else {
                thinkContent.classList.add('collapsed');
                toggleBtn.textContent = '展开';
            }
        }
    };

    // 初始化
    function init() {
        renderChatList();
        setupEventListeners();

        // 如果有聊天记录，激活第一个
        if (state.chats.length > 0) {
            setActiveChat(state.chats[0].id);
        } else {
            // 创建默认聊天
            createNewChat();
        }
    }

    // 设置事件监听器
    function setupEventListeners() {
        // 发送消息
        elements.sendBtn.addEventListener('click', sendMessage);
        elements.messageInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });

        // 新建聊天
        elements.newChatBtn.addEventListener('click', createNewChat);

        // 切换上传区域
        elements.uploadTabBtn.addEventListener('click', () => {
            elements.chatArea.classList.add('hidden');
            elements.uploadArea.classList.remove('hidden');
        });

        // 返回对话
        elements.backToChatBtn.addEventListener('click', () => {
            elements.uploadArea.classList.add('hidden');
            elements.chatArea.classList.remove('hidden');
        });

        // 文件上传相关
        elements.dropZone.addEventListener('click', () => elements.fileInput.click());
        elements.dropZone.addEventListener('dragover', (e) => {
            e.preventDefault();
            elements.dropZone.classList.add('border-green-500', 'bg-green-50');
        });
        elements.dropZone.addEventListener('dragleave', () => {
            elements.dropZone.classList.remove('border-green-500', 'bg-green-50');
        });
        elements.dropZone.addEventListener('drop', (e) => {
            e.preventDefault();
            elements.dropZone.classList.remove('border-green-500', 'bg-green-50');
            handleFiles(e.dataTransfer.files);
        });
        elements.fileInput.addEventListener('change', (e) => {
            handleFiles(e.target.files);
        });

        // 上传按钮
        elements.uploadBtn.addEventListener('click', uploadFiles);

        // 重命名相关
        elements.cancelRenameBtn.addEventListener('click', closeRenameModal);
        elements.confirmRenameBtn.addEventListener('click', confirmRename);

        // 监听知识库名称输入
        elements.ragTag.addEventListener('input', updateUploadButton);
    }

    // 处理文件选择
    function handleFiles(fileList) {
        state.filesToUpload = Array.from(fileList).filter(file => {
            const ext = file.name.split('.').pop().toLowerCase();
            return ['md', 'txt', 'sql'].includes(ext);
        });

        renderFileList();
        updateUploadButton();
    }

    // 渲染文件列表
    function renderFileList() {
        elements.fileList.innerHTML = '';

        if (state.filesToUpload.length === 0) {
            return;
        }

        state.filesToUpload.forEach((file, index) => {
            const fileElement = document.createElement('div');
            fileElement.className = 'flex items-center justify-between bg-gray-50 p-3 rounded-lg';
            fileElement.innerHTML = `
                    <div class="flex items-center">
                        <i class="fas fa-file text-gray-500 mr-3"></i>
                        <span class="text-sm">${file.name}</span>
                    </div>
                    <button class="text-red-500 hover:text-red-700 remove-file" data-index="${index}">
                        <i class="fas fa-times"></i>
                    </button>
                `;
            elements.fileList.appendChild(fileElement);
        });

        // 添加删除文件事件
        document.querySelectorAll('.remove-file').forEach(button => {
            button.addEventListener('click', (e) => {
                const index = parseInt(e.target.closest('.remove-file').dataset.index);
                state.filesToUpload.splice(index, 1);
                renderFileList();
                updateUploadButton();
            });
        });
    }

    // 更新上传按钮状态
    function updateUploadButton() {
        const hasFiles = state.filesToUpload.length > 0;
        const hasTag = elements.ragTag.value.trim() !== '';

        elements.uploadBtn.disabled = !(hasFiles && hasTag);
    }

    // 上传文件
    async function uploadFiles() {
        if (state.filesToUpload.length === 0 || !elements.ragTag.value.trim()) {
            showUploadStatus('请选择文件和输入知识库名称', 'error');
            return;
        }

        const formData = new FormData();
        formData.append('ragTag', elements.ragTag.value.trim());

        state.filesToUpload.forEach(file => {
            formData.append('file', file);
        });

        // 更新按钮状态
        elements.uploadBtn.disabled = true;
        elements.uploadBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>上传中...';

        try {
            const response = await fetch('http://localhost:8090/api/v1/rag/uploadFile', {
                method: 'POST',
                body: formData
            });

            const result = await response.json();

            if (result.code === '0000') {
                showUploadStatus('文件上传成功！', 'success');
                // 清空表单
                state.filesToUpload = [];
                elements.ragTag.value = '';
                renderFileList();
            } else {
                showUploadStatus(`上传失败: ${result.msg || '未知错误'}`, 'error');
            }
        } catch (error) {
            console.error('上传错误:', error);
            showUploadStatus('上传失败，请检查网络连接', 'error');
        } finally {
            elements.uploadBtn.disabled = false;
            elements.uploadBtn.innerHTML = '<i class="fas fa-upload mr-2"></i>开始上传';
            updateUploadButton();
        }
    }

    // 显示上传状态
    function showUploadStatus(message, type) {
        const colorClass = type === 'success' ? 'text-green-600' : 'text-red-600';
        elements.uploadStatus.innerHTML = `<p class="${colorClass}">${message}</p>`;

        // 3秒后清除状态
        setTimeout(() => {
            elements.uploadStatus.innerHTML = '';
        }, 3000);
    }

    // 创建新聊天
    function createNewChat() {
        const newChat = {
            id: Date.now().toString(),
            title: '新聊天',
            messages: [],
            createdAt: new Date().toISOString()
        };

        state.chats.unshift(newChat);
        saveChats();
        renderChatList();
        setActiveChat(newChat.id);
    }

    // 设置活动聊天
    function setActiveChat(chatId) {
        state.activeChatId = chatId;
        renderChatList();
        renderMessages();

        // 启用输入框
        elements.messageInput.disabled = false;
        elements.sendBtn.disabled = false;
    }

    // 渲染聊天列表
    function renderChatList() {
        elements.chatList.innerHTML = '';

        state.chats.forEach(chat => {
            const isActive = chat.id === state.activeChatId;
            const chatElement = document.createElement('div');
            chatElement.className = `p-3 rounded-lg cursor-pointer flex justify-between items-center ${isActive ? 'bg-blue-50 text-blue-700' : 'hover:bg-gray-100'}`;
            chatElement.innerHTML = `
                    <div class="flex-1 truncate" title="${chat.title}">${chat.title}</div>
                    ${isActive ? `
                    <div class="flex space-x-1 opacity-0 group-hover:opacity-100 transition-opacity">
                        <button class="text-gray-500 hover:text-blue-600 rename-chat" title="重命名">
                            <i class="fas fa-edit text-sm"></i>
                        </button>
                        <button class="text-gray-500 hover:text-red-600 delete-chat" title="删除">
                            <i class="fas fa-trash text-sm"></i>
                        </button>
                    </div>
                    ` : ''}
                `;

            // 点击聊天项
            chatElement.addEventListener('click', () => {
                setActiveChat(chat.id);
            });

            // 添加悬停效果显示操作按钮
            if (isActive) {
                chatElement.classList.add('group');
            }

            elements.chatList.appendChild(chatElement);
        });

        // 添加事件监听器到操作按钮
        document.querySelectorAll('.rename-chat').forEach(button => {
            button.addEventListener('click', (e) => {
                e.stopPropagation();
                openRenameModal(state.activeChatId);
            });
        });

        document.querySelectorAll('.delete-chat').forEach(button => {
            button.addEventListener('click', (e) => {
                e.stopPropagation();
                deleteChat(state.activeChatId);
            });
        });
    }

    // 打开重命名模态框
    function openRenameModal(chatId) {
        const chat = state.chats.find(c => c.id === chatId);
        if (chat) {
            elements.renameInput.value = chat.title;
            elements.renameModal.classList.remove('hidden');
        }
    }

    // 关闭重命名模态框
    function closeRenameModal() {
        elements.renameModal.classList.add('hidden');
    }

    // 确认重命名
    function confirmRename() {
        const newTitle = elements.renameInput.value.trim();
        if (newTitle) {
            const chat = state.chats.find(c => c.id === state.activeChatId);
            if (chat) {
                chat.title = newTitle;
                saveChats();
                renderChatList();
            }
        }
        closeRenameModal();
    }

    // 删除聊天
    function deleteChat(chatId) {
        if (confirm('确定要删除这个聊天吗？')) {
            state.chats = state.chats.filter(chat => chat.id !== chatId);
            saveChats();

            if (state.chats.length > 0) {
                setActiveChat(state.chats[0].id);
            } else {
                createNewChat();
            }
        }
    }

    // 渲染消息
    function renderMessages() {
        elements.messageList.innerHTML = '';

        const activeChat = state.chats.find(chat => chat.id === state.activeChatId);
        if (!activeChat || activeChat.messages.length === 0) {
            return;
        }

        activeChat.messages.forEach(message => {
            addMessageToUI(message, false);
        });

        // 滚动到底部
        scrollToBottom();
    }

    // 发送消息
    function sendMessage() {
        const messageText = elements.messageInput.value.trim();
        if (!messageText || state.isStreaming) return;

        // 创建用户消息
        const userMessage = {
            id: Date.now().toString(),
            role: 'user',
            content: messageText,
            timestamp: new Date().toISOString()
        };

        // 添加到当前聊天
        const activeChat = state.chats.find(chat => chat.id === state.activeChatId);
        activeChat.messages.push(userMessage);

        // 更新聊天标题（如果是第一条消息）
        if (activeChat.messages.length === 1) {
            activeChat.title = messageText.substring(0, 20) + (messageText.length > 20 ? '...' : '');
            saveChats();
            renderChatList();
        }

        // 清空输入框
        elements.messageInput.value = '';

        // 渲染用户消息
        addMessageToUI(userMessage, true);

        // 禁用输入
        elements.messageInput.disabled = true;
        elements.sendBtn.disabled = true;
        state.isStreaming = true;

        // 调用AI接口
        callAIStream(messageText);
    }

    // 调用AI流式接口
    function callAIStream(message) {
        // 创建AI消息占位符
        const aiMessage = {
            id: 'temp-' + Date.now().toString(),
            role: 'assistant',
            content: '',
            thinkContent: '',
            timestamp: new Date().toISOString()
        };

        // 添加到当前聊天
        const activeChat = state.chats.find(chat => chat.id === state.activeChatId);
        activeChat.messages.push(aiMessage);

        // 渲染AI消息占位符
        const messageElement = addMessageToUI(aiMessage, true);
        const contentElement = messageElement.querySelector('.message-content');
        contentElement.innerHTML = '<div class="loading-dots text-gray-500">思考中</div>';

        // 重置think管理器
        thinkManager.currentThinkContent = '';
        thinkManager.isInThinkBlock = false;

        // 构建API URL
        const apiUrl = `http://localhost:8090/api/v1/ollama/generate-stream?model=${state.currentModel}&message=${encodeURIComponent(message)}`;

        // 使用EventSource接收流式响应
        state.currentEventSource = new EventSource(apiUrl);

        state.currentEventSource.onmessage = function(event) {
            try {
                const data = JSON.parse(event.data);

                if (data.result && data.result.output && data.result.output.content) {
                    let content = data.result.output.content;

                    // 处理think块
                    if (content.includes('<think>')) {
                        thinkManager.startThink();
                        content = content.replace('<think>', '');
                    }

                    if (content.includes('</think>')) {
                        const thinkContent = thinkManager.endThink();
                        aiMessage.thinkContent = thinkContent;
                        content = content.replace('</think>', '');
                    }

                    // 如果在think块中，收集内容并实时显示
                    if (thinkManager.isInThinkBlock) {
                        thinkManager.addThinkContent(content);
                        // 这里移除了return，让思考内容也能实时显示
                        aiMessage.thinkContent = thinkManager.currentThinkContent;
                    } else {
                        // 更新消息内容
                        aiMessage.content += content;
                    }

                    // 渲染完整消息（包括think块和回答内容）
                    renderAIResponse(contentElement, aiMessage);
                }

                // 检查是否结束
                if (data.result && data.result.metadata &&
                    (data.result.metadata.finishReason === 'STOP' ||
                        data.result.metadata.finishReason === 'unknown')) {
                    finishStream();
                }
            } catch (error) {
                console.error('解析响应错误:', error);
            }
        };

        state.currentEventSource.onerror = function(event) {
            console.error('EventSource连接错误');
            finishStream();
        };

        // 完成流式响应
        function finishStream() {
            if (state.currentEventSource) {
                state.currentEventSource.close();
                state.currentEventSource = null;
            }

            // 更新消息ID（从临时ID改为永久ID）
            aiMessage.id = Date.now().toString();

            // 启用输入
            elements.messageInput.disabled = false;
            elements.sendBtn.disabled = false;
            state.isStreaming = false;

            // 保存聊天记录
            saveChats();

            // 滚动到底部
            scrollToBottom();

            // 高亮代码块
            setTimeout(() => {
                document.querySelectorAll('pre code').forEach((block) => {
                    hljs.highlightElement(block);
                });
            }, 100);
        }
    }

    // 渲染AI响应（包含think块和回答）
    function renderAIResponse(contentElement, aiMessage) {
        let contentHtml = '';

        // 如果有think内容，先渲染think块
        if (aiMessage.thinkContent && aiMessage.thinkContent.trim()) {
            contentHtml += thinkManager.renderThinkBlock(aiMessage.thinkContent);
        }

        // 渲染主要回答内容
        if (aiMessage.content && aiMessage.content.trim()) {
            try {
                const renderedContent = marked.parse(aiMessage.content);
                contentHtml += `<div class="markdown-content">${renderedContent}</div>`;
            } catch (error) {
                console.error('Markdown渲染错误:', error);
                contentHtml += `<div class="whitespace-pre-wrap">${aiMessage.content}</div>`;
            }
        }

        contentElement.innerHTML = contentHtml;
    }

    // 添加消息到UI
    function addMessageToUI(message, animate) {
        const messageElement = document.createElement('div');
        messageElement.className = `flex ${message.role === 'user' ? 'justify-end' : 'justify-start'}`;
        messageElement.id = `message-${message.id}`;

        if (animate) {
            messageElement.classList.add('message-fade-in');
        }

        let contentHtml;
        if (message.role === 'user') {
            contentHtml = `<div class="whitespace-pre-wrap">${message.content}</div>`;
        } else {
            // 对AI消息使用完整渲染
            contentHtml = renderAIResponseContent(message);
        }

        messageElement.innerHTML = `
                <div class="max-w-[80%] ${message.role === 'user' ? 'bg-blue-500 text-white' : 'bg-gray-200 text-gray-800'} rounded-2xl px-4 py-3">
                    <div class="message-content">${contentHtml}</div>
                </div>
            `;

        elements.messageList.appendChild(messageElement);
        scrollToBottom();

        return messageElement;
    }

    // 渲染AI响应内容（用于已保存的消息）
    function renderAIResponseContent(message) {
        let contentHtml = '';

        // 如果有think内容，先渲染think块
        if (message.thinkContent && message.thinkContent.trim()) {
            contentHtml += thinkManager.renderThinkBlock(message.thinkContent);
        }

        // 渲染主要回答内容
        if (message.content && message.content.trim()) {
            try {
                const renderedContent = marked.parse(message.content);
                contentHtml += `<div class="markdown-content">${renderedContent}</div>`;
            } catch (error) {
                console.error('Markdown渲染错误:', error);
                contentHtml += `<div class="whitespace-pre-wrap">${message.content}</div>`;
            }
        }

        return contentHtml;
    }

    // 滚动到底部
    function scrollToBottom() {
        setTimeout(() => {
            elements.chatArea.scrollTop = elements.chatArea.scrollHeight;
        }, 100);
    }

    // 保存聊天记录到本地存储
    function saveChats() {
        localStorage.setItem('aiChats', JSON.stringify(state.chats));
    }

    // 初始化应用
    init();
</script>
</body>
</html>